package com.gs.gms.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.gs.gms.common.exceptions.GmsDataAccessException;
import com.gs.gms.core.dao.impl.GmsCommonDaoImpl;
import com.gs.gms.dao.UserDao;
import com.gs.gms.model.entity.User;

@Repository
public class UserDaoImpl extends GmsCommonDaoImpl<User, Long> implements
		UserDao {

	private static Logger logger = Logger.getLogger(UserDaoImpl.class);
	
	
	public User getUserById(long id) throws GmsDataAccessException{
		try {
			return getEntityManager().find(User.class, id);
		} catch (Exception e) {
			logger.error(e);
			throw new GmsDataAccessException(e);
		}
	}
	
	public User saveUser(User user) throws GmsDataAccessException {
		try {
			getEntityManager().persist(user);
			getEntityManager().flush();
		} catch (Exception e) {
			logger.error(e);
			throw new GmsDataAccessException(e);
		}
		logger.info("Insert User, successful...");
		return user;
	}
	
	public List<User> getAllConnectedUsers(String userName)
			throws GmsDataAccessException {
		String jpql = "SELECT uc.connectedUser from User u, UserConnection uc"
				+ " where u.userName ='" + userName + "' " +
				" and u.userId = uc.sourceUser.userId "
				+ "and uc.connectionStatus ='ACTIVE'" ;
		try {
			List<User> conList = getEntityManager().createQuery(jpql).getResultList();
			return conList;
		} catch (Exception e) {
			throw new GmsDataAccessException(e);
		}
	}
}
